package main.java.com.dao.impl;

import main.java.com.config.BaseDao;
import main.java.com.dao.LoginFrontDao;
import main.java.com.entity.Employee;
import main.java.com.entity.User;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class LoginFrontDaoImpl extends BaseDao implements LoginFrontDao {
    Connection conn = null;
    PreparedStatement psmt = null;
    ResultSet rs = null;

    /**
     * 登录
     * @param phone 手机号码
     * @return
     */
    @Override
    public List<User> login(String phone) {
        List<User> employees = new ArrayList<>();
        conn = this.getConnection();
        String sql = "select * from user where phone = ?";
        try {
            psmt = conn.prepareStatement(sql);
            psmt.setString(1, phone);
            rs = psmt.executeQuery();
            User user = new User();
            while (rs.next()) {
                user.setId(rs.getLong("id"));
                user.setPhone(rs.getString("phone"));
            }
            if(user.getId() != null){
                employees.add(user);
            }
            //关闭
            closeAll(conn, psmt, rs);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return employees;
    }

    /**
     * 添加
     * @param phone
     * @return
     */
    @Override
    public int addUser(String phone) {
        int add = 0;
        conn = this.getConnection();
        //用户状态 ：status 和用户id
        String status = "1";
        String addsjs = addsjs();
        String sql = "insert into user(id,phone,status) value (?,?,?)";
        try {
            psmt = conn.prepareStatement(sql);
            psmt.setString(1, addsjs);
            psmt.setString(2, phone);
            psmt.setString(3, status);
            add = psmt.executeUpdate();
            //关闭
            closeAll(conn, psmt, rs);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return add;
    }

    /**
     * 生成用户id随机数方法
     */
    public String addsjs(){
        String add = "18";
        for (int i = 1; i <= 17; i++) {
            int sjs = (int) (Math.random()*10);
            add = add+""+sjs;
        }
        return add;
    }
}
